package com.miplus.ccrm.core.service.file;

import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.mashape.unirest.http.HttpResponse;
import com.mashape.unirest.http.JsonNode;
import com.mashape.unirest.http.Unirest;
import com.miplus.ccrm.common.EnumRCode;
import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.ServiceException;
import com.miplus.ccrm.core.controller.vo.file.ImageReqVo;
import com.miplus.ccrm.core.controller.vo.file.ImageResVo;
import com.miplus.ccrm.core.mapper.FiCreditcasesMapper;
import com.miplus.ccrm.core.mapper.IouBillMapper;
import com.miplus.ccrm.core.pojo.FiCreditcases;
import com.miplus.ccrm.core.pojo.IouBill;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class ImageService {
    @Value("${http.image.url}")
    public String imageUrl;

    @Resource
    private IouBillMapper iouBillMapper;

    public List<ImageResVo> quyFiles(ImageReqVo reqVo) {
        //String idnumber=fiCreditcasesMapper.getIdNumber(reqVo.getFicaseid());
        //if(JPubUtils.IsEmpty(idnumber)){
        //    throw new ServiceException(EnumRCode.NoFindSource.value, EnumRCode.NoFindSource.name);
        //}
        //String urlbody = imageUrl + "/getFiles?idCard=" + idnumber;

        IouBill bill=iouBillMapper.selectJoinOne(IouBill.class,new MPJLambdaWrapper<IouBill>()
                        .leftJoin(FiCreditcases.class,"fi",FiCreditcases::getCreditAcct,IouBill::getContractnumber)
                        .eq(FiCreditcases::getCreditcaseid,reqVo.getFicaseid())
        );
        String billno=bill.getBillid();
        String seqno=bill.getLoanSerialno();
        //先按照拮据号找，如没找到，再按照流水号找
        String urlbody = imageUrl + "/getFiles?applSeq=" + seqno;
        JSONArray jsonArray = sendHttpCmd(urlbody);
        if (jsonArray == null || jsonArray.length() == 0) {
            urlbody = imageUrl + "/getFiles?applSeq=" + billno;
            jsonArray = sendHttpCmd(urlbody);
        }
        if (jsonArray == null || jsonArray.length() == 0) {
            throw new ServiceException(EnumRCode.NoFindSource.value, EnumRCode.NoFindSource.name);
        }
        log.info("quyFiles:count={}", jsonArray.length());

        List<ImageResVo> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject p = jsonArray.getJSONObject(i);
            ImageResVo resVo = new ImageResVo();
            resVo.setApplSeq(JPubUtils.ObjectToString(p.get("applSeq")));
            resVo.setIdCard(JPubUtils.ObjectToString(p.get("idCard")));
            resVo.setAppOrigin(JPubUtils.ObjectToString(p.get("appOrigin")));
            resVo.setBusinessType(JPubUtils.ObjectToString(p.get("businessType")));
            resVo.setFileType(JPubUtils.ObjectToInt(p.get("fileType")));
            resVo.setFileId(JPubUtils.ObjectToString(p.get("fileId")));
            resVo.setGoodsKind(JPubUtils.ObjectToString(p.get("goodsKind")));
            resVo.setFileTypeDsc(getFileTypeDsc(resVo.getFileType()));

            list.add(resVo);
        }

        return list;
    }

    public String quyBase64(String fileId) {
        String urlbody = imageUrl + "/getBase64?fileId=" + fileId;
        return sendHttpAsString(urlbody);
    }

    public void quyImageStream(String fileId, HttpServletResponse response) {
        String imgData=quyBase64(fileId);
        if(JPubUtils.IsEmpty(imgData)){
            throw new ServiceException(EnumRCode.NoFindSource.value, EnumRCode.NoFindSource.name);
        }
        try {
            /* 读本地base64文件流方式
            String jpgfile="d:/java/y.txt";
            File file=new File(jpgfile);
            FileInputStream fis=new FileInputStream(file);
            BASE64Decoder decoder = new BASE64Decoder();
            ServletOutputStream out=response.getOutputStream();
            byte[] b=decoder.decodeBuffer(fis);
            out.write(b);
            */
            BASE64Decoder decoder = new BASE64Decoder();
            ServletOutputStream out=response.getOutputStream();
            byte[] buf = decoder.decodeBuffer(imgData);
            out.write(buf);

            out.flush();
            out.close();
        }
        catch (Exception e){
            JPubUtils.PrintError("quyImageStream", e);
            throw new ServiceException(EnumRCode.Exception.value, e.getMessage());
        }
    }

    private JSONArray sendHttpCmd(String urlbody) {
        log.info("sendHttpCmd:{}", urlbody);
        try {
            HttpResponse<JsonNode> jsonResponse = Unirest.get(urlbody).asJson();
            // 获取响应体
            log.debug("sendHttpCmd.Response:{}", jsonResponse);
            int status = jsonResponse.getStatus();
            if (status == 200) {
                JsonNode responseBody = jsonResponse.getBody();
                log.info("sendHttpCmd.ResponseBody:{}", responseBody);
                return responseBody.getArray();
            } else {
                log.warn("sendHttpCmd.Response:Fail={}", status);
                throw new ServiceException(EnumRCode.CmdFail.value, EnumRCode.CmdFail.name);
            }
        } catch (Exception e) {
            JPubUtils.PrintError("sendHttpCmd", e);
            throw new ServiceException(EnumRCode.Exception.value, e.getMessage());
        }
    }

    private String sendHttpAsString(String urlbody) {
        log.info("sendHttpAsString:{}", urlbody);
        try {
            HttpResponse jsonResponse = Unirest.get(urlbody).asString();
            // 获取响应体
            log.info("sendHttpCmd.Response:{}", jsonResponse);

            int status = jsonResponse.getStatus();
            if (status == 200) {
                String body = jsonResponse.getBody().toString();
                log.debug("sendHttpAsString.ResponseBody:{}", body);
                return body;
            } else {
                log.warn("sendHttpAsString.Response:Fail={}", status);
                throw new ServiceException(EnumRCode.CmdFail.value, EnumRCode.CmdFail.name);
            }
        } catch (Exception e) {
            JPubUtils.PrintError("sendHttpAsString", e);
            throw new ServiceException(EnumRCode.Exception.value, e.getMessage());
        }
    }

    private String getFileTypeDsc(Integer fileType) {
        switch (fileType) {
            case 3:
                return "身份证正面";
            case 4:
                return "身份证反面";
            case 5:
                return "人脸照片&手持身份证";
            case 6:
                return "征信授权书";
            case 7:
                return "三方授权书";
            case 8:
                return "借款协议";
            case 9:
                return "担保协议";
            case 10:
                return "金融服务费协议";
            case 11:
                return "医疗确认单";
            case 12:
                return "额度协议";
            case 13:
                return "个人信息授权书";
            case 14:
                return "担保服务费";
            case 15:
                return "委托扣款协议书";
            case 16:
                return "资方借款协议";
            case 17:
                return "学费确认单";
            case 18:
                return "授权书";
            case 19:
                return "个人借款额度合同";
            case 20:
                return "个人消费借款合同";
            case 21:
                return "共享平台授权书";
            case 22:
                return "委托投保合同";
            case 23:
                return "电子保单";
            case 24:
                return "投保单";
            case 25:
                return "行驶证";
            case 26:
                return "合格证";
            case 27:
                return "整车发票";
            case 28:
                return "保险变更申请书";
            case 29:
                return "客户手持身份证&保险变更申请书";
            case 30:
                return "保险批单";
            case 31:
                return "历史数据影像";
            case 32:
                return "电子档案";
            case 33:
                return "签章授权协议";
            case 34:
                return "担保函";
            case 35:
                return "委托快捷签署授权书";
            default:
                return "-";
        }
    }
}
